var treeTable;
var layuiTable;
var re;
$(function () {
    // 加载表格数据
    layuiTable=layui.table.render({
        elem: '#tableData'
        , url: '/sys/role/list/'
        ,toolbar: '#toolbarDemo'
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'roleId', title: 'ID', width: 100, unresize: true, sort: true, hide:true}
            , {field: 'roleName', title: '角色名称'}
            , {field: 'note', title: '备注'}
            ,{fixed: 'right', title:'操作', toolbar: '#bar', width:150}
        ]]
        ,id: 'testReload',
        page: true,
        limits: [20, 50, 100, 200],
        limit: 20
    });
    //头工具栏事件
    layui.table.on('toolbar(tableData)', function(obj){
        var checkStatus = layui.table.checkStatus(obj.config.id);
        switch(obj.event){
            case 'add':
                addForm();
                break;
        };
    });
    //监听行工具事件
    layui.table.on('tool(tableData)', function(obj){
        var data = obj.data;
        //删除
        if(obj.event === 'del'){
            layer.confirm('是否删除此记录？此操作不可恢复！', function(index){
                deleteTable(data);
                layer.close(index);
            });
        } else if(obj.event === 'edit'){
            editTable(data)
        }
    });

    var $ = layui.$, active = {
        reload: function(){
            var demoReload = $('#demoReload');
            //执行重载
            layui.table.reload('testReload', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where: {
                    roleName: demoReload.val()
                }
            });
        }
    };

    $('.demoTable .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
})

/*****刷新表格***********/
function reloadTable() {
    //这里以搜索为例
    layuiTable.reload('testReload', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
    });
}

/*******新增*********/
function addForm() {
    $("#roleId").attr("value",'');
    $("#formDiv input").val('');
    mentuTreeTable("list",null,null);
    layui.layer.open({
        type: 1,
        title: '新增',
        shadeClose: true,//点击遮罩关闭
        anim: 0,
        btnAlign: 'c',
        shade: 0.3,//是否有遮罩，可以设置成false
        maxmin: false, //开启最大化最小化按钮
        area: ['50%', '80%'],
        boolean: true,
        content:$('#formDiv'),
        success: function (layero, lockIndex) {
        },
        end: function () {
            $('#formDiv').hide();
        }
    });
}

/*****删除*******/
function deleteTable(data){
    $.ajax({
        url:"/sys/role/delete/"+data.roleId,
        type:"get",
        success:function (obj) {
            if (obj.code==0) {
                layer.msg(obj.msg, {
                    icon: 1,
                    shade: 0.3,
                    time: 2000
                }, function () {
                    //疯狂模式，关闭所有层
                    reloadTable();
                    parent.layer.closeAll();
                });
            } else {
                layer.msg(obj.msg, {
                    icon: 2,
                    shade: 0.3,
                    time: 1000
                });
            }
        }
    })

}


/*************编辑*************************/
function  editTable(data) {
    layui.layer.open({
        type: 1,
        title: '编辑',
        shadeClose: true,//点击遮罩关闭
        anim: 0,
        btnAlign: 'c',
        shade: 0.3,//是否有遮罩，可以设置成false
        maxmin: false, //开启最大化最小化按钮
        area: ['50%', '80%'],
        boolean: true,
        content:$('#formDiv'),
        success: function (layero, lockIndex) {
            $.ajax({
                url:"/sys/role/info/" +data.roleId,
                type:"get",
                success:function (r) {
                    if(r.code==0){
                        layui.use(['form'], function() {
                            //表单初始赋值
                            layui.form.val('form', {
                                "roleId": data.roleId
                                ,"roleName": r.data.roleName
                                ,"note": r.data.note
                            })
                            mentuTreeTable("list",null,r.data.menuId);
                        });
                    }else {
                        layer.msg(r.msg, {
                            icon: 2,
                            shade: 0.3,
                            time: 1000
                        });
                    }
                }
            })

        },
        end: function () {
            $('#formDiv').hide();
        }
    });
}

/*****************菜单树************/
function mentuTreeTable(type,data,check) {
    layui.config({
        base: '/static/plugins/layui/js/',
    })
    layui.use(['treeTable'],function(){
        treeTable = layui.treeTable;
        if(type=="list"){
            $.ajax({
                url:"/sys/menu/list",
                type:"GET",
                contentType: "application/json",
                success:function (r) {
                    if (r.code == 0) {
                        var arr=new Array();
                        $.each(r.data,function (index,en) {
                            var t=new Object();
                            t.id=en.menuId;
                            t.name=en.name;
                            t.pid=en.parentId;
                            arr.push(t);
                        });
                        arr.join(",")
                        //执行示例
                        re=treeTable.render({
                            elem: '#tree-table',
                            data:arr,
                            icon_key: 'name',
                            is_checkbox: true,
                            checked: {
                                key: 'id',
                                data:check,
                            },
                            cols: [
                                {
                                    key: 'name',
                                    title: '名称',
                                    width: '120px',
                                },
                                {
                                    key: 'id',
                                    title: 'id',
                                    width: '100px',
                                },
                                {
                                    key: 'pid',
                                    title: 'pid',
                                    width: '100px',
                                    align: 'center',
                                },
                            ]
                        });
                    }else{
                        layer.msg(r.msg, {
                            icon: 2,
                            shade: 0.3,
                            time: 1000
                        });
                    }
                    return false;
                }
            })
        }

        if(type=="add"){
            var url="/sys/role/save";
            if($('#roleId').val()!=""){
                url="/sys/role/update";
            }
            var temp=treeTable.checked(re).join(',');
            data.field.menuId=temp.split(",")

            $.ajax({
                url:url,
                type:"post",
                contentType: "application/json",
                data:JSON.stringify(data.field),
                success:function (r) {
                    if (r.code == 0) {
                        layer.msg(r.msg, {
                            icon: 1,
                            shade: 0.3,
                            time: 2000
                        }, function () {
                            //疯狂模式，关闭所有层
                            reloadTable();
                            parent.layer.closeAll();
                        });

                    }else{
                        layer.msg(r.msg, {
                            icon: 2,
                            shade: 0.3,
                            time: 1000
                        });
                    }
                }
            })
            return false;
        }
    })
}